package com.lhb.shiro;

import com.lhb.dao.PermissionMapper;
import com.lhb.dao.Repository.UserRepository;
import com.lhb.pojo.User;
import com.lhb.pojo.rep.TbPermissionReq;
import com.lhb.pojo.resp.TbPermissionResp;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.10.14 下午 17:16
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    UserRepository userRepository;

    @Autowired
    PermissionMapper permissionMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //1.获取到用户名
        String primaryPrincipal = (String) principalCollection.getPrimaryPrincipal();
        List<TbPermissionResp> list = permissionMapper.findByUserName(primaryPrincipal);
        Set set = new HashSet<>();
        for (TbPermissionResp tb : list) {
            set.add(tb.getTitle());
        }
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addStringPermissions(set);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        User byUserName = userRepository.findByUserName(principal);
        if (byUserName != null) {
            return new SimpleAuthenticationInfo(principal, byUserName.getUserPassword(), ByteSource.Util.bytes(principal), this.getName());
        }
        return null;
    }
}
